import { Book, BookArgs } from '../types/Book';
import { BaseRepository } from './BaseRepository';
import { relationalStore } from '@kit.ArkData';

export class BookRepository extends BaseRepository {

  private resultSetToItem(resultSet: relationalStore.ResultSet): Book {
    const book: Book = {
      id: resultSet.getLong(0),
      plugin_id: resultSet.getLong(1),
      type: resultSet.getString(2),
      name: resultSet.getString(3),
      url: resultSet.getString(4),
      cover: resultSet.getString(5),
      intro: resultSet.getString(6),
      author: resultSet.getString(7),
      tags: resultSet.getString(8),
      last_chapter_name: resultSet.getString(9),
      in_store: resultSet.getLong(10) === 1,
      last_read_chapter_id: resultSet.getLong(11),
      last_read_chapter_page: resultSet.getLong(12),
      create_at: resultSet.getLong(13),
      update_at: resultSet.getLong(14),
    }
    return book
  }

  async findByPluginIdAndUrl(plugin_id: number, url: string) {
    const resultSet = await this.db.querySql("select * from book where plugin_id = ? and url = ?", [plugin_id, url])
    const firstRow = resultSet.goToFirstRow();
    if (firstRow) {
      return this.resultSetToItem(resultSet)
    }
    return null
  }

  async findAll(): Promise<Book[]> {
    const result: Book[] = []
    const resultSet = await this.db.querySql("select * from book")
    const firstRow = resultSet.goToFirstRow();
    if (firstRow) {
      do {
        const book: Book = this.resultSetToItem(resultSet)
        result.push(book)
      } while (resultSet.goToNextRow())
    }
    return result
  }

  async findOne(id: number): Promise<Book | null> {
    const resultSet = await this.db.querySql("select * from book where id = ?", [id])
    const firstRow = resultSet.goToFirstRow();
    if (firstRow) {
      return this.resultSetToItem(resultSet)
    }
    return null
  }


  async create(book: BookArgs): Promise<number> {
    book.create_at = new Date().getTime()
    book.update_at = 0
    return await this.db.insert("book", book)
  }


  async update(id: number, book: BookArgs): Promise<number> {
    book.update_at = new Date().getTime()
    let predicates = new relationalStore.RdbPredicates("book");
    predicates.equalTo("id", id);
    return await this.db.update(book, predicates)
  }

  async delete(id: number): Promise<number> {
    let predicates = new relationalStore.RdbPredicates("book");
    predicates.equalTo("id", id);
    return await this.db.delete(predicates)
  }

}